# -*- coding: utf-8 -*-
# -------------------------------
# @文件：analysis_restful_testcase.py
# @时间：2024/3/26 17:47
# @作者：caiweichao
# @功能描述：解析 restful 接口测试用例
# -------------------------------
from util.basic.analysis_yaml import AnalysisYaml
from util.auto_test.api_test.case_model import ApiTestCase
from util.basic.get_env import get_env
from config.constants_path import DATA_PATH
from util.customize_exception import *
from util.auto_test.api_test.custom_parameters import call_back

import os
import re
import json
from urllib.parse import parse_qsl


class AnalysisRestfulTestCase:
    def __init__(self, file_url):
        self.file_url = os.path.join(DATA_PATH, file_url)
        self.file_data = AnalysisYaml(self.file_url).get_date()

    def analysis_testcase(self) -> list[ApiTestCase]:
        # 创建用例合集
        testcases: list[ApiTestCase] = []
        # 读取环境,获取指定环境的用例
        env = get_env()
        url = self.file_data["url"][env]
        method = self.file_data["method"].lower()
        for case in self.file_data["case_datas"]:
            # 过滤 excel 中的空行
            if case.get('env') is None:
                continue
            if env == str(case["env"]).lower():
                testcase = ApiTestCase()
                testcase.url = url
                testcase.method = method
                testcase.case_title = case["case_title"]
                if len(case["check"]) != len(case["result"]):
                    raise LenError(f"用例:--{testcase.case_title}--校验点和校验规则的数量不一致")
                testcase.check = case["check"]
                testcase.result = case["result"]
                case_data = str(case["case_data"])
                case_data = re.sub("#(.*?)#", call_back, case_data)
                if testcase.method == "get" and ("&" in case_data or "=" in case_data):
                    testcase.case_data = dict(parse_qsl(case_data))
                else:
                    testcase.case_data = json.loads(case_data)
                testcases.append(testcase)
        return testcases

if __name__ == '__main__':
    AnalysisRestfulTestCase("demo_service/demo_api.yaml").analysis_testcase()